{% extends "base.html" %}

{% block title %}生成文章 - 头条自动发文系统{% endblock %}
{% block page_title %}AI文章生成{% endblock %}

{% block content %}
<div class="row">
    <div class="col-md-4">
        <!-- 提示词输入 -->
        <div class="card mb-4">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-magic text-primary"></i>
                    文章生成
                </h5>
            </div>
            <div class="card-body">
                <form id="generate-form">
                    <div class="mb-3">
                        <label for="prompt" class="form-label">输入提示词</label>
                        <textarea id="prompt" name="prompt" class="form-control" rows="6" 
                                placeholder="请输入您想要生成的文章主题或要求...&#10;&#10;例如：&#10;- 写一篇关于人工智能发展的文章&#10;- 分享10个提高工作效率的技巧&#10;- 介绍最新的科技趋势"></textarea>
                    </div>
                    
                    <div class="d-grid">
                        <button type="submit" class="btn btn-gradient">
                            <span class="loading spinner-border spinner-border-sm me-2" role="status"></span>
                            <i class="fas fa-magic"></i>
                            生成文章
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- 提示词模板 -->
        <div class="card">
            <div class="card-header">
                <h5 class="mb-0">
                    <i class="fas fa-lightbulb text-warning"></i>
                    提示词模板
                </h5>
            </div>
            <div class="card-body">
                <div class="accordion" id="templateAccordion">
                    {% for category, prompts in prompt_templates.items() %}
                    <div class="accordion-item">
                        <h2 class="accordion-header" id="heading{{ loop.index }}">
                            <button class="accordion-button collapsed" type="button" 
                                    data-bs-toggle="collapse" data-bs-target="#collapse{{ loop.index }}">
                                {{ category }}
                            </button>
                        </h2>
                        <div id="collapse{{ loop.index }}" class="accordion-collapse collapse" 
                             data-bs-parent="#templateAccordion">
                            <div class="accordion-body">
                                {% for prompt in prompts %}
                                <div class="template-item mb-2">
                                    <button class="btn btn-outline-secondary btn-sm w-100 text-start template-btn" 
                                            data-prompt="{{ prompt }}">
                                        {{ prompt }}
                                    </button>
                                </div>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                    {% endfor %}
                </div>
            </div>
        </div>
    </div>
    
    <div class="col-md-8">
        <!-- 生成结果 -->
        <div class="card">
            <div class="card-header d-flex justify-content-between align-items-center">
                <h5 class="mb-0">
                    <i class="fas fa-file-alt text-success"></i>
                    生成结果
                </h5>
                <div id="result-actions" style="display: none;">
                    <button id="copy-btn" class="btn btn-outline-primary btn-sm">
                        <i class="fas fa-copy"></i>
                        复制内容
                    </button>
                    <button id="publish-btn" class="btn btn-success btn-sm">
                        <i class="fas fa-paper-plane"></i>
                        立即发布
                    </button>
                </div>
            </div>
            <div class="card-body">
                <!-- 默认提示 -->
                <div id="default-hint" class="text-center py-5">
                    <i class="fas fa-magic fa-3x text-muted mb-3"></i>
                    <h5 class="text-muted">AI文章生成器</h5>
                    <p class="text-muted">在左侧输入提示词，AI将为您生成高质量的文章内容</p>
                    <div class="row mt-4">
                        <div class="col-md-6">
                            <div class="border rounded p-3 mb-3">
                                <h6><i class="fas fa-lightbulb text-warning"></i> 生成特色</h6>
                                <ul class="list-unstyled text-muted small">
                                    <li><i class="fas fa-check text-success"></i> 自动分离标题和内容</li>
                                    <li><i class="fas fa-check text-success"></i> 适合头条发布格式</li>
                                    <li><i class="fas fa-check text-success"></i> 内容通俗易懂</li>
                                </ul>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="border rounded p-3 mb-3">
                                <h6><i class="fas fa-cog text-info"></i> 使用技巧</h6>
                                <ul class="list-unstyled text-muted small">
                                    <li><i class="fas fa-check text-success"></i> 提示词尽量具体</li>
                                    <li><i class="fas fa-check text-success"></i> 可指定字数要求</li>
                                    <li><i class="fas fa-check text-success"></i> 可要求特定风格</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- 生成中提示 -->
                <div id="generating-hint" style="display: none;" class="text-center py-5">
                    <div class="spinner-border text-primary mb-3" role="status">
                        <span class="visually-hidden">生成中...</span>
                    </div>
                    <h5 class="text-primary">AI正在生成文章...</h5>
                    <p class="text-muted">这可能需要几秒钟时间，请耐心等待</p>
                </div>
                
                <!-- 生成结果 -->
                <div id="result-content" style="display: none;">
                    <div class="mb-4">
                        <label class="form-label fw-bold">文章标题</label>
                        <input type="text" id="article-title" class="form-control form-control-lg" readonly>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">文章内容</label>
                        <textarea id="article-content" class="form-control" rows="15" readonly></textarea>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label fw-bold">
                            封面图片 
                            <span class="text-danger">*</span>
                            <small class="text-muted">(必需)</small>
                        </label>
                        <div id="cover-section">
                            <div id="no-cover">
                                <div class="input-group mb-2">
                                    <input type="file" id="cover-image-file" class="form-control" accept="image/*" required>
                                    <button type="button" id="upload-cover-generate" class="btn btn-outline-secondary" disabled>
                                        <span class="loading spinner-border spinner-border-sm me-1" role="status"></span>
                                        <i class="fas fa-upload"></i>
                                        上传
                                    </button>
                                </div>
                                <div class="form-text">
                                    <span class="text-danger">
                                        <i class="fas fa-exclamation-triangle"></i>
                                        封面图片是发布的必需条件
                                    </span><br>
                                    选择JPG、PNG等图片格式，建议尺寸16:9
                                </div>
                            </div>
                            <div id="cover-preview" style="display: none;">
                                <img id="cover-image" src="" alt="封面图片" class="img-fluid rounded" style="max-width: 100%; max-height: 300px;">
                                <div class="mt-2">
                                    <small class="text-success">
                                        <i class="fas fa-check-circle"></i>
                                        封面图片已上传
                                    </small>
                                    <button id="remove-cover-generate" class="btn btn-sm btn-outline-danger ms-2">
                                        <i class="fas fa-times"></i>
                                        移除
                                    </button>
                                </div>
                            </div>
                        </div>
                        <input type="hidden" id="cover-path-generate" value="">
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                            <small class="text-muted">
                                <i class="fas fa-info-circle"></i>
                                字数统计：<span id="word-count">0</span> 字
                            </small>
                        </div>
                        <div class="col-md-6 text-end">
                            <small class="text-muted">
                                <i class="fas fa-clock"></i>
                                生成时间：<span id="generate-time"></span>
                            </small>
                        </div>
                    </div>
                </div>
                
                <!-- 错误提示 -->
                <div id="error-hint" style="display: none;" class="text-center py-5">
                    <i class="fas fa-exclamation-triangle fa-3x text-warning mb-3"></i>
                    <h5 class="text-warning">生成失败</h5>
                    <p id="error-message" class="text-muted"></p>
                    <button id="retry-btn" class="btn btn-primary">
                        <i class="fas fa-redo"></i>
                        重新生成
                    </button>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 发布确认模态框 -->
<div class="modal fade" id="publishModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="fas fa-paper-plane text-success"></i>
                    确认发布文章
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>确定要立即发布这篇文章吗？</p>
                <div class="alert alert-info">
                    <i class="fas fa-info-circle"></i>
                    文章将会发布到您当前登录的头条账号
                </div>
                <div class="alert alert-warning">
                    <i class="fas fa-exclamation-triangle"></i>
                    请确保已上传封面图片，封面图片是发布的必需条件
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" id="confirm-publish" class="btn btn-success">
                    <span class="loading spinner-border spinner-border-sm me-2" role="status"></span>
                    <i class="fas fa-paper-plane"></i>
                    确认发布
                </button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    let currentArticle = null;
    let currentCoverPath = null;
    
    // 提交生成表单
    $('#generate-form').submit(function(e) {
        e.preventDefault();
        
        const prompt = $('#prompt').val().trim();
        if (!prompt) {
            showAlert('请输入提示词', 'warning');
            return;
        }
        
        generateArticle(prompt);
    });
    
    // 生成文章
    function generateArticle(prompt) {
        // 显示生成中状态
        $('#default-hint').hide();
        $('#result-content').hide();
        $('#error-hint').hide();
        $('#generating-hint').show();
        $('#result-actions').hide();
        
        // 禁用生成按钮
        showLoading('#generate-form button[type="submit"]', true);
        
        // 调用API
        $.post('/api/generate-article', {prompt: prompt})
            .done(function(response) {
                if (response.success) {
                    // 显示生成结果
                    currentArticle = response;
                    $('#article-title').val(response.title);
                    $('#article-content').val(response.content);
                    $('#word-count').text(response.content.length);
                    $('#generate-time').text(new Date().toLocaleString());
                    
                    $('#generating-hint').hide();
                    $('#result-content').show();
                    $('#result-actions').show();
                    
                    // 重置封面区域
                    $('#cover-preview').hide();
                    $('#no-cover').show();
                    $('#cover-image-file').val('');
                    $('#cover-path-generate').val('');
                    $('#upload-cover-generate').prop('disabled', true);
                    currentCoverPath = null;
                    
                    // 保存当前文章信息
                    currentArticle = {
                        title: response.title,
                        content: response.content
                    };
                    
                    showAlert('文章生成成功！', 'success');
                } else {
                    showError(response.message);
                }
            })
            .fail(function() {
                showError('生成文章时发生网络错误');
            })
            .always(function() {
                showLoading('#generate-form button[type="submit"]', false);
            });
    }
    
    // 显示错误
    function showError(message) {
        $('#generating-hint').hide();
        $('#result-content').hide();
        $('#error-message').text(message);
        $('#error-hint').show();
        $('#result-actions').hide();
    }
    
    // 重新生成
    $('#retry-btn').click(function() {
        const prompt = $('#prompt').val().trim();
        if (prompt) {
            generateArticle(prompt);
        }
    });
    
    // 模板按钮点击
    $('.template-btn').click(function() {
        const prompt = $(this).data('prompt');
        $('#prompt').val(prompt);
        
        // 自动生成
        generateArticle(prompt);
    });
    
    // 复制内容
    $('#copy-btn').click(function() {
        const title = $('#article-title').val();
        const content = $('#article-content').val();
        const fullText = `标题：${title}\n\n内容：\n${content}`;
        
        navigator.clipboard.writeText(fullText).then(function() {
            showAlert('内容已复制到剪贴板', 'success');
        }).catch(function() {
            showAlert('复制失败，请手动复制', 'warning');
        });
    });
    
    // 立即发布
    $('#publish-btn').click(function() {
        if (!currentArticle) {
            showAlert('没有可发布的文章', 'warning');
            return;
        }
        
        $('#publishModal').modal('show');
    });
    
    // 确认发布
    $('#confirm-publish').click(function() {
        if (!currentArticle || !currentCoverPath) return;
        
        showLoading(this, true);
        
        $.post('/api/publish-article', {
            title: currentArticle.title,
            content: currentArticle.content,
            cover_image: currentCoverPath
        })
        .done(function(response) {
            if (response.success) {
                showAlert('文章发布成功！', 'success');
                $('#publishModal').modal('hide');
                
                // 可以跳转到监控页面
                setTimeout(function() {
                    window.location.href = '/monitor';
                }, 2000);
            } else {
                showAlert(response.message, 'danger');
            }
        })
        .fail(function() {
            showAlert('发布失败，请重试', 'danger');
        })
        .always(function() {
            showLoading('#confirm-publish', false);
        });
    });
    
    // 图片文件选择处理
    $('#cover-image-file').change(function() {
        const file = this.files[0];
        if (file) {
            // 文件类型验证
            if (!file.type.startsWith('image/')) {
                showAlert('请选择图片文件', 'warning');
                $(this).val('');
                return;
            }
            
            // 文件大小验证（10MB）
            if (file.size > 10 * 1024 * 1024) {
                showAlert('图片文件不能超过10MB', 'warning');
                $(this).val('');
                return;
            }
            
            // 显示预览
            const reader = new FileReader();
            reader.onload = function(e) {
                $('#cover-image').attr('src', e.target.result);
                $('#cover-preview').show();
            };
            reader.readAsDataURL(file);
            
            $('#upload-cover-generate').prop('disabled', false);
        } else {
            $('#upload-cover-generate').prop('disabled', true);
            $('#cover-preview').hide();
        }
    });
    
    // 上传封面图片
    $('#upload-cover-generate').click(function() {
        const fileInput = $('#cover-image-file')[0];
        const file = fileInput.files[0];
        
        if (!file) {
            showAlert('请先选择图片文件', 'warning');
            return;
        }
        
        const formData = new FormData();
        formData.append('file', file);
        
        showLoading(this, true);
        
        $.ajax({
            url: '/api/upload-cover',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    $('#cover-path-generate').val(response.file_path);
                    currentCoverPath = response.file_path;
                    showAlert('封面图片上传成功', 'success');
                    $('#upload-cover-generate').text('已上传').addClass('btn-success').removeClass('btn-outline-secondary');
                } else {
                    showAlert(response.message, 'danger');
                }
            },
            error: function() {
                showAlert('图片上传失败，请重试', 'danger');
            },
            complete: function() {
                showLoading('#upload-cover-generate', false);
            }
        });
    });
    
    // 移除封面图片
    $('#remove-cover-generate').click(function() {
        $('#cover-image-file').val('');
        $('#cover-path-generate').val('');
        $('#cover-preview').hide();
        $('#upload-cover-generate').prop('disabled', true).text('上传').removeClass('btn-success').addClass('btn-outline-secondary');
        currentCoverPath = null;
    });
    
    // 立即发布
    $('#publish-btn').click(function() {
        if (!currentArticle) {
            showAlert('没有可发布的文章', 'warning');
            return;
        }
        
        if (!currentCoverPath) {
            showAlert('请先上传封面图片，封面图片是发布的必需条件', 'warning');
            return;
        }
        
        $('#publishModal').modal('show');
    });
    
    // 字数统计更新
    $('#article-content').on('input', function() {
        const count = $(this).val().length;
        $('#word-count').text(count);
    });
});
</script>
{% endblock %}
